package com.cv.framework.file.config;

import me.desair.tus.server.TusFileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * Tus 协议 - 文件上传自动配置类
 *
 * @author Charles_XDXD
 */
@AutoConfiguration
public class CvFileAutoConfiguration {

    @Value("${os.win.localStorage.path}")
    private String osWinLocalStoragePath;

    @Value("${os.linux.localStorage.path}")
    private String osLinuxLocalStoragePath;

    @Value("${os.mac.localStorage.path}")
    private String osMacLocalStoragePath;

    @Bean
    public TusFileUploadService tusFileUploadService() {
        TusFileUploadService tusFileUploadService = new TusFileUploadService();

        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            tusFileUploadService.withStoragePath(osWinLocalStoragePath + "/tus");
        } else if (os.contains("mac")) {
            tusFileUploadService.withStoragePath(osMacLocalStoragePath + "/tus");
        } else {
            tusFileUploadService.withStoragePath(osLinuxLocalStoragePath + "/tus");
        }

        tusFileUploadService.withUploadURI("/infra/file/upload");
        tusFileUploadService.withThreadLocalCache(true);

        return tusFileUploadService;
    }

    @PreDestroy
    public void exit() throws IOException {
        tusFileUploadService().cleanup();
    }

}
